<p>It is equivalent to use the equality <code>==</code> operator and the <code>equals</code> method to compare two objects if the <code>equals</code>
method inherited from <code>Object</code> has not been overridden. In this case both checks compare the object references.</p>
<p>But as soon as <code>equals</code> is overridden, two objects not having the same reference but having the same value can be equal. This rule spots
suspicious uses of <code>==</code> and <code>!=</code> operators on objects whose <code>equals</code> methods are overridden.</p>
<h2>Noncompliant Code Example</h2>
<pre>
String firstName = getFirstName(); // String overrides equals
String lastName = getLastName();

if (firstName == lastName) { ... }; // Non-compliant; false even if the strings have the same value
</pre>
<h2>Compliant Solution</h2>
<pre>
String firstName = getFirstName();
String lastName = getLastName();

if (firstName != null &amp;&amp; firstName.equals(lastName)) { ... };
</pre>
<h2>Exceptions</h2>
<p>Comparing two instances of the <code>Class</code> object will not raise an issue:</p>
<pre>
Class c;
if(c == Integer.class) { // No issue raised
}
</pre>
<p>Comparing <code>Enum</code> will not raise an issue:</p>
<pre>
public enum Fruit {
   APPLE, BANANA, GRAPE
}
public boolean isFruitGrape(Fruit candidateFruit) {
  return candidateFruit == Fruit.GRAPE; // it's recommended to activate S4551 to enforce comparison of Enums using ==
}
</pre>
<p>Comparing with <code>final</code> reference will not raise an issue:</p>
<pre>
private static final Type DEFAULT = new Type();

void foo(Type other) {
  if (other == DEFAULT) { // Compliant
  //...
  }
}
</pre>
<p>Comparing with <code>this</code> will not raise an issue:</p>
<pre>
  public boolean equals(Object other) {
    if (this == other) {  // Compliant
      return false;
    }
 }
</pre>
<p>Comparing with <code>java.lang.String</code> and boxed types <code>java.lang.Integer</code>, …​ will not raise an issue.</p>
<h2>See</h2>
<ul>
  <li> {rule:java:S4973} - Strings and Boxed types should be compared using "equals()" </li>
  <li> <a href="https://cwe.mitre.org/data/definitions/595.html">MITRE, CWE-595</a> - Comparison of Object References Instead of Object Contents </li>
  <li> <a href="https://cwe.mitre.org/data/definitions/597.html">MITRE, CWE-597</a> - Use of Wrong Operator in String Comparison </li>
  <li> <a href="https://wiki.sei.cmu.edu/confluence/x/UjdGBQ">CERT, EXP03-J.</a> - Do not use the equality operators when comparing values of boxed
  primitives </li>
  <li> <a href="https://wiki.sei.cmu.edu/confluence/x/yDdGBQ">CERT, EXP50-J.</a> - Do not confuse abstract object equality with reference equality
  </li>
</ul>

